import AddCircleIcon from '@mui/icons-material/AddCircle';
import {
    Box,
    CircularProgress,
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableRow,
    Typography
} from '@mui/material';
import { useRouter } from 'next/router';
import React, { useEffect, useState } from 'react';

import PayrollGroup from '../../api/payroll-group/payroll-group';
import PayrollGroupManager from '../../api/payroll-group/payroll-group-manager';
import PayrollGroupMember from '../../api/payroll-group-member/payroll-group-member';
import MainLayout from '../../components/HOCs/main-layout';
import { addScholarDialog } from '../../components/members/add-member-popup';
import PayrollGroupHeader from '../../components/payroll-group/payroll-group-header';
import { GFSButton } from '../../components/shared/button/gfs-button';
import RemoveButton from '../../components/shared/button/remove-button';
import { createDialog } from '../../components/shared/dialogs/dynamic-dialogs';
import { DialogTypes } from '../../components/shared/dialogs/dynamic-dialogs/types-mapping';
import GFSTable from '../../components/shared/tables/gfs-table';
import { useInfiniteScroll } from '../../hooks/infinitive-scroll';
import { useLoadPayrollGroupMembers } from '../../hooks/payroll-group-members-load-more';

const PayrollGroupPage = () => {
    const router = useRouter();
    const [payrollGroupID, setPayrollGroupID] = useState(null);
    const [payrollGroup, setPayrollGroup] = useState<PayrollGroup>(undefined);
    const [payrollGroupMembers, setPayrollGroupMembers] = useState<PayrollGroupMember[]>(null);
    const [pageLoading, setPageLoading] = useState(true);
    const { loading, items, hasNextPage, error, loadMore } =
        useLoadPayrollGroupMembers(payrollGroupID);

    const [sentryRef] = useInfiniteScroll({
        loading,
        hasNextPage,
        onLoadMore: loadMore,
        disabled: !!error,
        rootMargin: '0px 0px 400px 0px'
    });

    useEffect(() => {
        if (!router.isReady) return;
        const { id } = router.query;
        setPayrollGroupID(id);
    }, [router.isReady]);

    useEffect(() => {
        const load = async () => {
            await loadMore();
            setPageLoading(false);
        };

        if (payrollGroupID) {
            getPayrollGroupInfo();
            load().then();
        }
    }, [payrollGroupID]);

    useEffect(() => {
        setPayrollGroupMembers(items);
    }, [items]);

    const getPayrollGroupInfo = () => {
        if (payrollGroupID) {
            PayrollGroupManager.getByID(payrollGroupID).then((payrollGroup: PayrollGroup) => {
                setPayrollGroup(payrollGroup);
            });
        }
    };

    const onDelete = (payrollGroupMember: PayrollGroupMember) => {
        const updated = payrollGroupMembers.filter((item) => item.id != payrollGroupMember.id);
        setPayrollGroupMembers(updated);
        getPayrollGroupInfo();
    };

    const openCreateDialog = () => {
        createDialog(DialogTypes.ADD_SCHOlAR, () => {
            addScholarDialog({
                open: true,
                onSubmit: handleAfterAddScholar,
                data: {
                    payrollGroupMembers: payrollGroupMembers
                }
            });
        });
    };

    const handleAfterAddScholar = (members: PayrollGroupMember[]) => {
        setPayrollGroupMembers([...members, ...payrollGroupMembers]);
        getPayrollGroupInfo();
    };

    return (
        <MainLayout>
            <Box
                sx={{
                    backgroundColor: '#0B0821',
                    padding: 6
                }}
            >
                {payrollGroup === null && (
                    <Typography variant="h2">Payroll Group not found.</Typography>
                )}

                {payrollGroup && <PayrollGroupHeader payrollGroup={payrollGroup} />}

                {payrollGroupMembers && payrollGroupMembers.length == 0 && (
                    <Typography
                        variant="h2"
                        sx={{
                            mt: 1,
                            mb: 2
                        }}
                    >
                        No members yet.
                    </Typography>
                )}
                <GFSButton onClick={openCreateDialog} sx={{ ml: 3 }}>
                    <AddCircleIcon sx={{ mr: 1 }} />
                    Add member
                </GFSButton>

                {!pageLoading && (
                    <Box sx={{ pb: 4 }}>
                        {!error ? (
                            <>
                                {payrollGroupMembers && payrollGroupMembers.length > 0 && (
                                    <GFSTable>
                                        <Table
                                            sx={{
                                                minWidth: 650,
                                                marginTop: 5
                                            }}
                                            aria-label="Disbursement List"
                                        >
                                            <TableHead>
                                                <TableRow>
                                                    <TableCell>Name</TableCell>
                                                    <TableCell align="center">
                                                        Email Address
                                                    </TableCell>
                                                    <TableCell align="center">
                                                        Earning Share
                                                    </TableCell>
                                                    <TableCell align="center" width="150px" />
                                                </TableRow>
                                            </TableHead>
                                            <TableBody>
                                                {payrollGroupMembers.map(
                                                    (payrollGroupMember: PayrollGroupMember) => {
                                                        return (
                                                            <TableRow
                                                                key={payrollGroupMember.member.id}
                                                            >
                                                                <TableCell>
                                                                    <Box
                                                                        component="img"
                                                                        sx={{
                                                                            height: '30px',
                                                                            width: '30px',
                                                                            marginRight: '10px'
                                                                        }}
                                                                        alt="Member"
                                                                        src="/member.png"
                                                                    />
                                                                    {payrollGroupMember.member.name}
                                                                </TableCell>
                                                                <TableCell align="center">
                                                                    {
                                                                        payrollGroupMember.member
                                                                            .email
                                                                    }
                                                                </TableCell>
                                                                <TableCell align="center">
                                                                    {payrollGroup?.memberShare}%
                                                                </TableCell>
                                                                <TableCell align="center">
                                                                    <RemoveButton
                                                                        onDelete={onDelete}
                                                                        payrollGroupMember={
                                                                            payrollGroupMember
                                                                        }
                                                                    />
                                                                </TableCell>
                                                            </TableRow>
                                                        );
                                                    }
                                                )}
                                            </TableBody>
                                        </Table>
                                    </GFSTable>
                                )}
                                {sentryRef && (loading || hasNextPage) && (
                                    <Box
                                        display="flex"
                                        justifyContent="center"
                                        alignItems="center"
                                        sx={{ pt: 4 }}
                                    >
                                        <CircularProgress
                                            ref={sentryRef}
                                            sx={{ color: '#ffffff' }}
                                        />
                                    </Box>
                                )}
                            </>
                        ) : (
                            error?.message && (
                                <Typography
                                    className="mt-4"
                                    sx={{ color: 'var(--color-negative)' }}
                                >
                                    Something went wrong!
                                </Typography>
                            )
                        )}
                    </Box>
                )}
            </Box>
        </MainLayout>
    );
};

export default PayrollGroupPage;
